# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 -------------------------------------------------
    File Name:     runtest.py
    Description:   
 -------------------------------------------------
 """

from core.basecase import BaseCase, ENV
from core.DBClient import db as db_obj
from core import testtools
from core.postman import environment

if __name__ == '__main__':
    # 测试用例数据
    case = {
        "title": "登陆",
        "interface": {
            "url": "/api/users/login",
            # 如果是项目外的第三方接口，url应该是一个完整的地址：https://www.baidu.com/api/users/register/
            "method": "post"
        },
        "headers": {
            "Content-Type": "application/json"
        },
        "request": {
            "params": {},
            "data": {
                "username": 1234
            },
            "json": {
                "username": "${{username}}",
                "password": "admin123456"
            },
            "files": {}
        },
        "setup_script": open("setup_script.txt", 'r', encoding='utf-8').read(),
        "teardown_script": open("teardown_script.txt", 'r', encoding='utf-8').read(),
    }

    # 测试环境
    test_env = {
        # 基础地址
        "base_url": "http://127.0.0.1:8000",
        # 默认请求头
        "headers": {
            "Content-Type": "application/json"
        },
        # 环境变量
        "Envs": {
            "username": "test",
        },
        "functools": open("tools.py", 'r', encoding="utf-8").read(),
        # 数据库配置
        "db": [
            {
                "name": "test",
                "type": "mysql",
                "config": {
                    "host": "127.0.0.1",
                    "port": 3306,
                    "user": "root",
                    "password": "Hell12345..",
                }
            }
        ]
    }

    # 根据数据库的配置初始化数据库的连接
    db_obj.init_connect(test_env.pop('db'))

    # 将测试环境中的数据加载到ENV中
    ENV.update(test_env)  # 更新环境变量
    environment.update(test_env.get('Envs'))  # 更新环境变量
    # print(environment)
    # 执行functools.py文件中的代码
    # 通过exec将字符串中的python变量加载到functools这个模块的命令空间中
    exec(ENV.get("functools"), testtools.__dict__)

    # 在这里实话化时，ENV已被更新
    BaseCase().perform(case)

    # 关闭数据库连接
    db_obj.close_db_connection()
